<template>
  <div class="delivery">
    <el-container>
      <el-header height="150px">
        <el-card header="出库登记">
          <el-container>
            <el-aside style="float:right; text-align: right; width: 88%">
              <el-popover
                placement="left"
                width="600px"
                trigger="click">
                <el-table :data="materialDatas.slice((mcurrentPage-1)*mpageSize,mcurrentPage*mpageSize)">
                  <el-table-column width="200" property="name" label="物料名称"></el-table-column>
                  <el-table-column width="150" property="specification" label="型号及规格"></el-table-column>
                  <el-table-column width="150" property="unit" label="单位"></el-table-column>
                  <el-table-column width="150" property="type" label="物料类型"></el-table-column>
                  <el-table-column width="150" property="storeNum" label="库存"></el-table-column>
                </el-table>
                <!-- 分页器 -->
                <div class="block" style="margin-top: 15px;">
                  <el-pagination
                    :current-page.sync="mcurrentPage"
                    :page-size="mpageSize"
                    layout="total, prev, pager, next, jumper"
                    :total="materialDatas.length">
                  </el-pagination>
                </div>
                <el-button slot="reference" >查询物料信息表</el-button>
              </el-popover>
            </el-aside>
          </el-container>
        </el-card>
      </el-header>
      <el-main>
        <el-col :xs="24">
          <el-card>
            <el-table  :data="primaryTableData.slice((pCurrentPage-1)*pPageSize,pCurrentPage*pPageSize)" :row-key='getRowKeys' v-loading="loading" @expand-change="rowExpand" :expand-row-keys="expands" >
              <el-table-column prop="id" label="id" v-if="false"/>
              <el-table-column prop="requisitionId" label="领用编号"/>
              <el-table-column prop="acceptId" label="验收编号"/>
              <el-table-column prop="provider" label="供货单位"/>
              <el-table-column prop="department" label="领料部门"/>
              <el-table-column prop="receiver" label="收料人"/>
              <el-table-column prop="createtime" label="申请时间"/>
              <el-table-column prop="status" label="领用状态"/>
              <el-table-column prop="principal" label="物料负责人" v-if="false"/>
              <el-table-column prop="sender" label="发料人" v-if="false"/>
              <el-table-column prop="departLeader" label="部门领导"/>
              <el-table-column prop="companyLeader" label="单位领导"/>
              <el-table-column width="200px" label="操作">
                <template slot-scope="scope">
                  <el-button
                    mc-type="column-el-button"
                    size="mini"
                    type="primary"
                    @click="handleExport(scope.$index, scope.row)">导出</el-button>
                </template>
              </el-table-column>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-col :xs="24">
                    <el-card>
                      <el-table :data="subTableMap.get(scope.row.requisitionId).slice((currentPage-1)*pageSize,currentPage*pageSize)" :row-key='getRowKeys' :fit="true" :show-header="true">
                        <el-table-column prop="id" label="id" sortable="true" v-if="false"></el-table-column>
                        <el-table-column prop="requisitionId" label="领料编号" v-if="false"></el-table-column>
                        <el-table-column prop="name" label="物资名称"></el-table-column>
                        <el-table-column prop="specification" label="型号及规格"></el-table-column>
                        <el-table-column prop="unit" label="计量单位"></el-table-column>
                        <el-table-column prop="dueNum" label="应发数量"></el-table-column>
                        <el-table-column prop="actualNum" label="实发数量"></el-table-column>
                        <el-table-column prop="price" label="单价"></el-table-column>
                        <el-table-column prop="tax" label="税率"></el-table-column>
                        <el-table-column prop="remark" label="备注"></el-table-column>
                        <el-table-column fixed="right" width="200px" label="操作">
                          <template slot-scope="scope">
                            <el-button
                              mc-type="column-el-button"
                              size="mini"
                              type="primary"
                              @click="handleEdit(scope.$index, scope.row)">编 辑</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                      <el-pagination style="margin-left: -5px;" layout="prev,pager,next" :page-size="pageSize" :total="subTableMap.get(scope.row.requisitionId).length" :current-page.sync="currentPage"></el-pagination>
                      <el-button-group>
                        <el-button id="btnDeliver" @click="handleDeliver(scope.row)" type="primary">出 库</el-button>
                        <el-button id="btnCancel" @click="handleCancel(scope.row)" type="warning">退 回</el-button>
                      </el-button-group>
                    </el-card>
                  </el-col>
                </template>
              </el-table-column>
            </el-table>
            <!-- 主表分页 -->
            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="primaryTableData.length"
              :current-page.sync="pCurrentPage"
              :page-size="pPageSize"
              style="text-align: center">
            </el-pagination>
          </el-card>
        </el-col>
      </el-main>
    </el-container>
    <!--编辑领料单内容弹窗-->
    <el-dialog title="修改物料出库信息" :visible.sync="editFormVisible" :before-close="handleEditClose" width="30%">
      <el-form class="action-form" :model="updForm" label-width="100px">
        <el-form-item label="实发数量">
          <el-input v-model="updForm.actualNum" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="updForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormCancel()">取 消</el-button>
        <el-button type="primary" @click="editFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<script src="exceljs.js"></script>
<script>
import { initStoreInform, initPrimaryTable, initSubTableSource, updateMaterialRequisition, deliveryCancel, deliveryConfirm } from '@/api/material-delivery/delivery'
import { getToken } from '@/utils/auth'
import saveAs from "file-saver"

export default {
  name: 'Deliver',
  data() {
    return {
      editFormVisible: false, // 编辑框是否可见
      loading: true,
      updForm: {
        index: '',
        id: '',
        requisitionId: '',
        actualNum: '',
        remark: '无'
      },

      // 查询物料信息表数据源及分页
      materialDatas: [],
      mcurrentPage: 1,
      mpageSize: 5,

      pageSize: 5,
      currentPage: 1,
      // pageTotal: 10,
      getRowKeys(row) {
        return row.id
      },
      expands: [],
      subTableMap: null,
      pPageSize: 5,
      pCurrentPage: 1,
      primaryTableData: [
      ],
      headers: {
        Authorization: getToken()
      },
      requisitionHeaders: [
      ],
      details: [
      ]
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      initStoreInform().then((response) => {
        this.materialDatas = response.data
      })
      initPrimaryTable().then((response) => {
        this.primaryTableData = response.data
      })
      initSubTableSource().then((response) => {
        this.details = response.data
        this.subTableMap = new Map()
        // 防止出现子表为空时出错的现象
        for (let i = 0, len = this.primaryTableData.length; i < len; ++i) {
          this.subTableMap.set(this.primaryTableData[i].requisitionId, [])
        }
        for (let i = 0, len = this.details.length; i < len; ++i) {
          const item = this.details[i]
          if (!this.subTableMap.has(item.requisitionId)) {
            this.subTableMap.set(item.requisitionId, [item])
          } else {
            this.subTableMap.get(item.requisitionId).push(item)
          }
        }
      })
      this.loading = false
    },
    rowExpand(row, expandeRows) {
      if (expandeRows.length) {
        // this.expands = []
        if (row) {
          // 展开新页时需要把子表的当前页置为1
          this.currentPage = 1
          this.expands = [row.id]
          // this.expands.push(row.id)
        } else {
          this.expands = [1]
        }
      } else {
        this.expands = []
      }
    },
    async handleExport(index, row) {
      const Excel = require('exceljs')
      const workbook = new Excel.Workbook()
      // 设置第一行第一列冻结
      const sheet = workbook.addWorksheet('Sheet1', {views:[{xSplit: 1, ySplit:1}]})
      // 数据写入
      // 先获取使用的工作表
      const worksheet = workbook.getWorksheet('Sheet1')
      const title_alignment = {
        vertical: 'middle',
        horizontal: 'center'
      }
      const title_font_style = {
        name: '宋体',
        family: 4,
        size: 16,
        underline: false,
        bold: true
      }
      worksheet.mergeCells('A1:K1')
      worksheet.getCell('A1').value = '物资领料单'
      // 设置对齐方式
      worksheet.getCell('A1').alignment = title_alignment
      // 字体样式
      worksheet.getCell('A1').font = title_font_style

      worksheet.mergeCells('A2:C2')
      worksheet.getCell('A2').value = '收货单位：' + row.department
      worksheet.mergeCells('A3:C3')
      worksheet.getCell('A3').value = '供货单位：' + row.provider
      worksheet.mergeCells('I3:K3')
      worksheet.getCell('I3').value = '编号：' + row.requisitionId
      const materialRequisitions = []
      const datasource = this.subTableMap.get(row.requisitionId)
      for (let i = 0, len = datasource.length; i < len; ++i) {
        materialRequisitions[i] = {
          index: i + 1,
          name: datasource[i].name,
          specification: datasource[i].specification,
          unit: datasource[i].unit,
          dueNum: datasource[i].dueNum,
          actualNum: datasource[i].actualNum,
          price: datasource[i].price,
          priceAmount: datasource[i].price * datasource[i].actualNum,
          tax: datasource[i].tax,
          taxAmount: datasource[i].price * datasource[i].actualNum * datasource[i].tax,
          remark: datasource[i].remark
        }
      }
      worksheet.columns = [
        // { header: '', key: 'remark', width: 10 },
        // 不设置表头，需要自行合并单元格
        { key: 'index', width: 10 },
        { key: 'name', width: 16 },
        { key: 'specification', width: 10 },
        { key: 'unit', width: 10 },
        { key: 'dueNum', width: 10 },
        { key: 'actualNum', width: 10 },
        { key: 'price', width: 10 },
        { key: 'priceAmount', width: 10 },
        { key: 'tax', width: 10 },
        { key: 'taxAmount', width: 10 },
        { key: 'remark', width: 18 },
      ]
      // 设置表头
      const headerDisplay = {
        index: '序号',
        name: '货物名称',
        specification: '规格型号',
        unit: '单位',
        dueNum: '应收',
        actualNum: '实收',
        price: '单价',
        priceAmount: '金额',
        tax: '税率',
        taxAmount: '税额',
        remark: '备注'
      }
      worksheet.addRow(headerDisplay)
      let priceAmount = 0, taxAmount = 0
      for(let i = 0; i < materialRequisitions.length; ++i) {
        worksheet.addRow(materialRequisitions[i]);
        priceAmount += materialRequisitions[i].priceAmount
        taxAmount += materialRequisitions[i].taxAmount
      }
      let rowCount = 3 + materialRequisitions.length + 2
      worksheet.mergeCells('A' + rowCount + ':D' + rowCount)
      worksheet.getCell('A' + rowCount).value = '合计'
      worksheet.getCell('A' + rowCount).alignment = title_alignment
      worksheet.getCell('H' + rowCount).value = priceAmount // 金额
      worksheet.getCell('J' + rowCount).value = taxAmount // 税额
      worksheet.getCell('K' + rowCount).value = '' // 空单元格
      ++rowCount
      worksheet.getCell('B' + rowCount).value = '物资负责人：'
      worksheet.getCell('C' + rowCount).value = row.principal
      worksheet.getCell('G' + rowCount).value = '发料人：'
      worksheet.getCell('H' + rowCount).value = row.sender
      worksheet.getCell('J' + rowCount).value = '收料人：'
      worksheet.getCell('K' + rowCount).value = row.receiver
      // 设置边框
      const body_top = 4, body_bottom = rowCount - 1,
        body_left = 1, body_right = 11
      // 这种分类方式较复杂，但正好不重不漏
      for (let i = 4; i < rowCount; ++i) {
        const cur = worksheet.getRow(i)
        cur.eachCell({ includeEmpty: true }, function(cell, j) {
          if (i === body_top && j === body_left) { // 左上
            cell.border = {
                  top: {style:'thick'},
                  left: {style:'thick'},
                }
          } else if (i === body_top && j === body_right) { // 右上
            cell.border = {
              top: {style:'thick'},
              left: {style:'thin'},
              right: {style:'thick'}
            }
          } else if (i === body_bottom && j === body_right) { // 右下
            cell.border = {
              top: {style:'thin'},
              left: {style:'thin'},
              bottom: {style:'thick'},
              right: {style:'thick'}
            }
          } else if (i === body_bottom && j === 4) { // 左下
            cell.border = {
              top: {style:'thin'},  // 233
              left: {style:'thick'},
              bottom: {style:'thick'}
            }
          } else if (i === body_top) {
            cell.border = {
              top: {style:'thick'},
              left: {style:'thin'}
            }
          } else if (i === body_bottom) {
            cell.border = {
              top: {style:'thin'}, // 233
              left: {style:'thin'},
              bottom: {style:'thick'}
            }
          } else if (j === body_left) {
            cell.border = {
              top: {style:'thin'},
              left: {style:'thick'}
            }
          } else if (j === body_right) {
            cell.border = {
              top: {style:'thin'},
              left: {style:'thin'},
              right: {style:'thick'}
            }
          } else {
            cell.border = {
              top: {style:'thin'},
              left: {style:'thin'}
            }
          }
        })
      }
      await workbook.xlsx.writeBuffer().then(function (buffer) {
        saveAs(
          new Blob([buffer], { type: "application/octet-stream" }),
          row.requisitionId + '.xlsx'
        )
      })
      return

      const headers = [
        'index',
        'name',
        'specification',
        'unit',
        'dueNum',
        'actualNum',
        'price',
        'priceAmount',
        'tax',
        'taxAmount',
        'remark'
      ]
    },
    handleDeliver(row) {
      this.$confirm('是否确认出库？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deliveryInfo = {
          requisitionHeader: row,
          materialRequisitionList: this.subTableMap.get(row.requisitionId)
        }
        deliveryConfirm(deliveryInfo).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消出库'
        })
      })
    },
    handleCancel(row) {
      this.$confirm('是否退回该领料申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deliveryCancel(row.requisitionId).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          this.init()
          this.expands = [1]
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },
    handleEdit(index, row) {
      this.editFormVisible = true
      this.updForm.index = index
      this.updForm.id = row.id
      this.updForm.requisitionId = row.requisitionId
      this.updForm.actualNum = row.actualNum
      if (row !== '') {
        this.updForm.remark = row.remark
      }
    },
    handleEditClose() {
      this.editFormCancel()
    },
    editFormCancel() {
      this.editFormVisible = false
      this.updForm.index = ''
      this.updForm.id = ''
      this.updForm.requisitionId = ''
      this.updForm.actualNum = ''
      this.updForm.remark = '无'
    },
    editFormConfirm() {
      this.editFormVisible = false
      updateMaterialRequisition(
        this.updForm
      ).then((response) => {
        this.$message.success(response.message)
        this.loading = true
        this.init()
        this.updForm.index = ''
        this.updForm.id = ''
        this.updForm.requisitionId = ''
        this.updForm.actualNum = ''
        this.updForm.remark = '无'
      }).catch((error) => {
        console.log(error)
      })
    }
  }
}
</script>

<style scoped>

</style>
